<template>
	<view class="container flex-c">
		<image class="left img" :src="require('@/public/images/public/dhl_fhb.png')" mode="aspectFit" @tap="$goBack()"></image>
		<view class="head flex-c">
			<text class="hello">您好！</text>
			<text class="welcome">欢迎登录彩虹体育</text>
		</view>
		<keep-alive>
		<view class="body flex-c" v-if="!passwordLogin">
			<view class="title">验证码登录</view>
			<view class="input-box flex-r ac">
				<input class="input text-regular" name="phone" type="number" placeholder="请输入手机号" placeholder-style="color:#B3B3B3;" v-model="phone" @input="inputPhone" :maxlength="11" step="1"/>
				<uni-icons class="clear-icon" v-show="phone != ''" type="clear" color="#B3B3B3" size="36rpx" @tap="phone = ''"></uni-icons>
			</view>
			<view class="input-box flex-r ac mt20">
				<input class="input text-regular" name="smscode" type="number" placeholder="请输入验证码" placeholder-style="color:#B3B3B3;" v-model="smscode" @input="inputCode" :focus="codefocus" :maxlength="6" step="1"/>
				<text class="sendcode text-regular color-blue" @touchend.prevent="sendSmsCode" @tap="sendSmsCode">{{sendText}}</text>
			</view>
			<view class="privacy flex-r ac" @tap="checkBox">
				<image :src="privacyCheck ? require('@/public/images/public/xy_xz.png') : require('@/public/images/public/xy_wxz.png')" mode="aspectFit"></image>
				<view class="text text-small color-grey">
					<text>我已阅读并接受</text>
					<text class="color-blue" @tap.stop="$CHS.goAbout('service')">《用户服务协议》</text><text class="color-blue" @tap.stop="$CHS.goAbout('privacy')">《隐私政策》</text>
				</view>
			</view>
			<view class="submit-box">
				<button type="default" class="button" :class="{'active': canSubmit}" @tap="submitCodeLogin" :loading="loading">登录</button>
			</view>
			<view class="other-login text-secondary color-blue">
				<text @tap="switchLogin">密码登录</text>
			</view>
			<!-- <template v-if="isWeixin">
				<view class="line flex-r ac jc">
					<text></text>
					<text class="line-text text-small color-grey">其他方式</text>
					<text></text>
				</view>
				<view class="weixin-login flex-c ac" @tap="weixinLogin">
					<image src="@/public/images/public/wxdl.png" mode="aspectFit"></image>
					<text class="text-small mt20">微信登录</text>
				</view>
			</template> -->
		</view>
		<view class="body flex-c" v-else>
			<view class="title">密码登录</view>
			<view class="input-box flex-r ac">
				<input class="input text-regular" name="phone" type="number" placeholder="请输入手机号" placeholder-style="color:#B3B3B3;" v-model="phone" @input="inputPhone" :maxlength="11"/>
				<uni-icons class="clear-icon" v-show="phone != ''" type="clear" color="#B3B3B3" size="36rpx" @tap="phone = ''"></uni-icons>
			</view>
			<view class="input-box flex-r ac mt20">
				<input class="input text-regular" name="password" type="password" placeholder="请输入密码" placeholder-style="color:#B3B3B3;" v-model="password" :focus="codefocus"/>
				<uni-icons class="clear-icon" v-show="password != ''" type="clear" color="#B3B3B3" size="36rpx" @tap="password = ''"></uni-icons>
			</view>
			<view class="privacy flex-r ac" @tap="checkBox">
				<image :src="privacyCheck ? require('@/public/images/public/xy_xz.png') : require('@/public/images/public/xy_wxz.png')" mode="aspectFit"></image>
				<view class="text text-small color-grey">
					<text>我已阅读并接受</text>
					<text class="color-blue" @tap.stop="$CHS.goAbout('service')">《用户服务协议》</text><text class="color-blue" @tap.stop="$CHS.goAbout('privacy')">《隐私政策》</text>
				</view>
			</view>
			<view class="submit-box">
				<button type="default" :class="{'active': canSubmit}" @tap="submitPwdLogin" :loading="loading">登录</button>
			</view>
			<view class="other-login text-secondary color-blue flex-r ac jc">
				<text class="right" @tap="switchLogin">验证码登录</text>
				<text class="fenge">|</text>
				<text @tap="$Router.push({name: 'forgotpassword'})">忘记密码</text>
			</view>
		</view>
		</keep-alive>
	</view>
</template>

<script>
	import imMsg from "@/utils/common/message.js";
	export default {
		data() {
			return {
				phone: '', //手机号
				smscode: '', //验证码
				password: '', //密码
				
				passwordLogin: false, //是否密码登录
				privacyCheck: false, //是否已勾选隐私协议
				codefocus: false, //验证码输入框聚焦
				isSend: false, //验证码是否已发送
				isSubmit: false, //是否已提交
				loading: false, //加载状态
				
				sendText: '获取验证码' //发送验证码提示文字
			}
		},
		computed:{
			canSend() { //验证手机号
				return this.phone != '' && this.phone.length == 11 && /^[1][3-9][\d]{9}/.test(this.phone)
			},
			canSubmit() { //检查输入
				if(this.passwordLogin){
					return this.canSend && this.password != '' && this.password.length >= 6 && this.privacyCheck
				}else{
					return this.canSend && this.smscode != '' && this.smscode.length == 6 && this.privacyCheck
				}
			},
			isWeixin() {//微信
				//判断客户端类型
				let ua = navigator.userAgent.toLowerCase();
				//是否在微信打开
				if (ua.match(/micromessenger/i) == "micromessenger"){
					return true
				}else{
					return false
				}
			}
		},
		onLoad() {
			//登录后回跳地址
			this.redirectTo = this.$CHS.getRedirectTo()
			//本地手机号
			this.phone = uni.getStorageSync('user_phone') || ''
			//清理遗留缓存
			sessionStorage.removeItem('signrule')
			sessionStorage.removeItem('growthrule')
			sessionStorage.removeItem('awardrule')
			const launchOptions = uni.getLaunchOptionsSync()
			// if(this.redirectTo=='articledetail'){
			// 	uni.navigateBack()
			// }
		},
		onUnload() {
			if(this.timer){
				clearInterval(this.timer)
				this.timer = null
			}
		},
		methods: {
			//切换登录方式
			switchLogin() {
				this.passwordLogin = !this.passwordLogin
				if(this.passwordLogin){
					this.smscode = ''
				}else{
					this.password = ''
				}
			},
			//发送短信验证码
			sendSmsCode() {
				if(!this.canSend){ //确认是否输入正确的手机号
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return
				}
				if(this.isSend){ //防止重复发送
					return
				}
				this.isSend = true
				this.sendText = '发送中...'
				this.$CHS.sendSmsCode({
					phone: this.phone,
					term: 'user',
					type: 0 //0 .登录模板、1.注册模板、2.忘记密码模板
				}).then((res)=>{
					let time = 60
					this.sendText = '重新获取 ' + time + 's'
					this.timer = setInterval(()=>{
						time = time - 1
						if(time === 0){
							clearInterval(this.timer)
							this.isSend = false
							this.timer = null
							this.sendText = '获取验证码'
						}else{
							this.sendText = '重新获取 ' + time + 's'
						}
					}, 1000)
					this.codefocus = true
				}).catch((err)=>{
					this.isSend = false
					this.sendText = '获取验证码'
				})
			},
			//验证码登录提交
			submitCodeLogin() {
				if(this.isSubmit || !this.canSubmit) {
					if(!this.privacyCheck) {
						uni.showToast({
							title: '请阅读并接受用户服务协议与隐私政策',
							icon: 'none',
						})
					}
					return
				}
				this.isSubmit = true
				this.loading  = true
				let loginModel = this.$CHS.getInviteCode()
				this.$http.post({
					url: '/api/smsLogin',
					data:{
						smscode: this.smscode,
						username: this.phone,
						term: 'user',
						...loginModel
					}
				}).then((data)=>{
					if(data.success && data.result){
						//保存用户信息
						this.$store.commit('SET_USERINFO', data.result)
						console.log(this.redirectTo,'回跳地址')
						//更新IM用户资料，跳转首页或来源页面
						setTimeout(()=>{
							imMsg.login(data.result.userInfo).then((ready) => {
								this.isSubmit = false
								//登录成功提示
								this.$ShowToast({text: '登录成功'})
								//查询优惠活动
								this.$CHS.getCouponActivity(data.result.userInfo.userId)
								//跳转网址
								if(data.result.userInfo.isFirstRegistration === true){//首次登录
									this.$Router.replaceAll({name: 'followseason'})
								}else if(this.redirectTo){//存在回跳地址
									this.$Router.replaceAll(this.redirectTo)
								}else{//跳转首页
									this.$Router.replaceAll({name: 'index'})
								}
								/*
								let random = this.$CHS.randomString(10) + Date.now()
								this.$Router.replaceAll({name: 'downlead', params: {random}})
								*/
							}).catch((err)=>{
								console.log(err,'登录失败');
								this.isSubmit = false
								//登录错误提示
								this.$ShowToast({text: '登录失败，请重试', type: 2, time: 3})
								this.$store.commit('SET_USERINFO', {})
							})
						}, 200)
					}else{
						this.isSubmit = false
						if(data.code == 10077 || data.code == 10006 ){//账号注销停用
							uni.showModal({
								title: '系统提示',
								content: '当前手机号已注销，请更换手机号或重新申请注册',
								confirmText: '重新注册',
								cancelText: '更换手机号',
								success: (res) => {
									if (res.confirm) {
										this.$Router.push({name: 'resetlogin', params: {phone: this.phone}})
									} else {
										this.smscode = ''
										this.phone = ''
									}
								}
							})
						}else{
							uni.showModal({
								title: '系统提示',
								content: data.message,
								showCancel: false,
							})
						}
					}
					this.loading = false
				}).catch((err)=>{
					console.log(err);
					this.isSubmit = false
					this.loading = false
					uni.showToast({
						title: '登录失败，请稍后重试',
						icon: 'none'
					})
				})
			},
			//密码登录提交
			submitPwdLogin() {
				if(this.isSubmit){
					return
				}
				if(!this.canSend){
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none',
					})
					return
				}
				if(!this.canSubmit) {
					uni.showToast({
						title: '请输入登录密码',
						icon: 'none',
					})
					return
				}
				if(!this.privacyCheck) {
					uni.showToast({
						title: '请阅读并接受用户服务协议与隐私政策',
						icon: 'none',
					})
					return
				}
				this.isSubmit = true
				this.loading  = true
				//设置专家邀请码
				let loginModel = this.$CHS.getInviteCode()
				this.$http.post({
					url: '/api/mLogin',
					data:{
						password: this.password,
						username: this.phone,
						term: 'user',
						...loginModel
					}
				}).then((data)=>{
					if(data.success && data.result){
						//保存用户信息
						this.$store.commit('SET_USERINFO', data.result)
						//更新IM用户资料，跳转首页或来源页面
						setTimeout(()=>{
							imMsg.login(data.result.userInfo).then((ready) => {
								this.isSubmit = false
								//登录成功提示
								this.$ShowToast({text: '登录成功'})
								//查询优惠活动
								this.$CHS.getCouponActivity(data.result.userInfo.userId)
								//跳转网址
								if(data.result.userInfo.isFirstRegistration === true){
									//this.$Router.replaceAll({name: 'completeinfo'})
									this.$Router.replaceAll({name: 'followseason'})
								}else if(this.redirectTo){
									this.$Router.replaceAll(this.redirectTo)
								}else{
									this.$Router.replaceAll({name: 'index'})
								}
							}).catch((err)=>{
								this.isSubmit = false
								//登录提示
								this.$ShowToast({text: '登录失败，请重试', type: 2, time: 3})
								this.$store.commit('SET_USERINFO', {})
							})
						}, 200)
					}else{
						this.isSubmit = false
						if(data.code == 10077 || data.code == 10006 ){
							uni.showModal({
								title: '系统提示',
								content: '当前手机号已注销，请更换手机号或重新申请注册',
								confirmText: '重新注册',
								cancelText: '更换手机号',
								success: (res) => {
									if (res.confirm) {
										this.$Router.push({name: 'resetlogin', params: {phone: this.phone}})
									} else {
										this.password = ''
										this.phone = ''
									}
								}
							})
						}else{
							uni.showModal({
								title: '系统提示',
								content: data.message,
								showCancel: false,
							})
						}
					}
				}).catch((err) => {
					this.isSubmit = false
					uni.showToast({
						title: '登录失败，请稍后重试',
						icon: 'none'
					})
				}).finally(()=>{
					this.loading = false
					uni.setStorageSync('user_phone', this.phone)
				})
			},
			//微信登录
			weixinLogin() {
				if(!this.privacyCheck) {
					uni.showToast({
						title: '请阅读并接受用户服务协议与隐私政策',
						icon: 'none',
					})
					return
				}
				let random = this.$CHS.randomString(10) + Date.now()
				this.$goByName('weixinlogin', {random})
			},
			//输入手机号
			inputPhone(e) {
				if(e.detail.value && e.detail.value.length == 11){
					if(/^[1][3-9][\d]{9}/.test(e.detail.value)){
						this.codefocus = true
					}else{
						uni.showToast({
							title: '请输入正确的手机号',
							icon: 'none'
						});
					}
				}
			},
			//输入验证码
			inputCode(e) {
				if(e.detail.value && e.detail.value.length == 6){
					this.codefocus = false
					uni.hideKeyboard()
				}
			},
			//协议选中状态切换
			checkBox() {
				this.privacyCheck = !this.privacyCheck
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background-color: #0055FF;
		background-image: url("~@/public/images/public/dl_bg.png");
		background-size: 100%;
		background-repeat: no-repeat;
		background-position: 0 -40rpx;
		padding: 0 30rpx;
		min-height: var(--safe-height);
		.img{
			width: 40rpx;
			height: 100rpx;
		}
		.head{
			padding-top: 40rpx;
			color: #FFFFFF;
			.hello{
				font-size: 60rpx;
				font-weight: 500;
			}
			.welcome{
				margin-top: 26rpx;
				font-size: 30rpx;
			}
		}
		.body {
			margin: 90rpx 0 40rpx;
			padding: 0 30rpx;
			background: #FFFFFF;
			border-radius: 20rpx;
			.title {
				margin: 60rpx 0 20rpx;
				font-size: 48rpx;
				font-weight: 500;
			}
			.input-box{
				border-bottom: 1rpx solid #EDEDED;
				.input{
					flex: 2;
					border: none;
					height: 120rpx;
				}
				.clear-icon{
					width: 60rpx;
					height: 120rpx;
					line-height: 120rpx;
				}
				.sendcode{
					padding: 30rpx 0;
				}
			}
			.privacy{
				margin-top: 30rpx;
				image {
					width: 32rpx;
					height: 32rpx;
				}
				.text{
					margin-left: 10rpx;
				}
			}
			.submit-box{
				margin-top: 50rpx;
			}
			.other-login{
				text-align: center;
				margin: 30rpx 0 40rpx;
				.color-blue{
					flex: 2;
					&.right{
						text-align: right;
					}
				}
				.fenge{
					margin: 0 40rpx;
				}
			}
			.line{
				margin-bottom: 30rpx;
				text:first-child, text:last-child{
					width: 160rpx;
					height: 1rpx;
					background: #B3B3B3;
				}
				.line-text{
					margin: 0 30rpx;
					color: #999999;
				}
			}
			.weixin-login{
				margin-bottom: 60rpx;
				image{
					width: 96rpx;
					height: 96rpx;
				}
			}
		}
		.weixin{
			padding: 20rpx;
		}
	}
</style>
